package com.hank.filter;

import com.hank.dto.UserDTO;
import com.hank.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * @author gaoZhiHao
 * @date 2023/5/5 11:51
 */
@Component
public class UserContextFilter implements Filter {
    private static final ThreadLocal<UserDTO> currentUser = new ThreadLocal<>();

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String authToken = httpRequest.getHeader("Authorization");

        UserDTO user = null;
        if (authToken != null) {
            // 解析 authToken 获取用户信息
            user = parseUserFromAuthToken(authToken);
        }

        try {
            // 将用户信息保存到 ThreadLocal 变量中
            currentUser.set(user);
            chain.doFilter(request, response);
        } finally {
            // 在请求处理结束后清空 ThreadLocal 变量
            currentUser.remove();
        }
    }

    @Override
    public void destroy() {

    }

    public static UserDTO getCurrentUser() {
        return currentUser.get();
    }

    private UserDTO parseUserFromAuthToken(String authToken) {
        // 解析 authToken 并返回对应的 User 对象
        return jwtUtils.parseToken(authToken);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

}

